<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\api\traits\ModelController;
use App\Http\Controllers\api\traits\ResponseController;
use Request;

class ResourceController
{
    use ResponseController, ModelController;

    public function showExt(&$model){
        if (Request::get('with')) {
            $model->load(Request::get('with'));
        }
        if (Request::get('attr')) {
            foreach (Request::get('attr') as $attr) {
                if (str_contains($attr, '.')) {
                    $attr_tree = explode('.', $attr);
                    $length=sizeof($attr_tree);
                    $attribute = $model;
                    for($i=0;$i<$length;$i++){
                        $key=$attr_tree[$i];
                        if($i!=$length-1){
                            $attribute = $attribute->$key;
                        }else{
                            $value     = $attribute->$key;
                        }
                    }
                    $attribute->setAttribute($key, $value);
                } else {
                    /** @var Model $model */
                    $model->setAttribute($attr, $model->{$attr});
                }
            }
        }
    }
}
